package intranet.controllers;

import intranet.tools.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.*;

import java.net.URLEncoder;
import java.sql.Timestamp;
import java.util.Date;
import javax.servlet.ServletConfig;
import javax.servlet.ServletRequest;

import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.*;
import intranet.forms.UploadItem;
import intranet.models.FileCategoryModel;
import intranet.models.MyuploadModel;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/uploadfile")
public class UploadFileController {
	private String uploadFolderPath;
	ServletConfig config;

	public String getUploadFolderPath() {
		return uploadFolderPath;
	}

	public void setUploadFolderPath(String uploadFolderPath) {
		this.uploadFolderPath = uploadFolderPath;
	}

	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView getUploadForm(Model model,String failed_msg, ServletRequest request,HttpServletResponse response,HttpSession session) throws SQLException, IOException {
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			model.addAttribute(new UploadItem());
			//Passing Page Included
			mv.addObject("includethispage", "file_sharing/myupload/upload.jsp");
			
			// Passing File Category
			FileCategoryModel mycat=new FileCategoryModel();
			ResultSet rscat=mycat.SelectFileCategory(0);
			ArrayList cat=this.resultSetToArrayList(rscat);
			mv.addObject("categories",cat);
			
			// Passing current category
			String fileCategory=request.getParameter("category");
			mv.addObject("category", fileCategory);
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}

	@RequestMapping(method = RequestMethod.POST)
	public void create(UploadItem uploadItem,BindingResult result,HttpServletRequest request, HttpServletResponse response,HttpSession session) throws IOException {
		if (result.hasErrors()) {	
			for (ObjectError error : result.getAllErrors()) {
				System.err.println("Error: " + error.getCode() + " - "
						+ error.getDefaultMessage());
			}
			response.sendRedirect("upload_failed.html");
		}

		// Some type of file processing...
		//System.err.println("-------------------------------------------");
		try {
			MultipartFile file = uploadItem.getFileData();
			InputStream inputStream = null;
			OutputStream outputStream = null;
			
			String fileTitle=request.getParameter("txttitle");
			String fileCategory=request.getParameter("txtcat");
			String fileDescription=request.getParameter("txtdesc");
			String fileKeyword=request.getParameter("txtkeyword");
			
			if (file.getSize() > 0) {
				inputStream = file.getInputStream();
				//if (file.getSize() > 10485760  1073741824 1610612736 ) 
				//Upload upto 1.5GB
				if (file.getSize()> 1610612736) {
					//mv.addObject("isFileSizeError",isFileSizeError);
					//mv.addObject("includethispage", "file_sharing/myupload/upload_filesize_failed.jsp");
					response.sendRedirect("uploadfile.html?title="+URLEncoder.encode(fileTitle,"UTF-8")+"&category="+URLEncoder.encode(fileCategory,"UTF-8")+"&description="+URLEncoder.encode(fileDescription,"UTF-8")+"&keywords="+URLEncoder.encode(fileKeyword,"UTF-8")+"");
				}else{
					/* Change file name */
				    Date today = new Date();
				    Timestamp timestp=new java.sql.Timestamp(today.getTime());
				    Cryptography crpy=new Cryptography();
				    String encrttimestp=crpy.encrypt(timestp.toString());
				    
				    /*Generate Upload Path*/
					WebConfig webcon=new WebConfig();
					/* Get current user name - use as an upload folder */
					String uploadPath=webcon.getPATH()+"users\\member\\"+encrttimestp+"_"+file.getOriginalFilename();
				//filePath ="C:\\images\\"
				//		+ encrttimestp +"_"+file.getOriginalFilename();
					outputStream = new FileOutputStream(uploadPath);
				//System.out.println("fileName:" + file.getOriginalFilename());

					int readBytes = 0;
					byte[] buffer = new byte[10485760];
					while ((readBytes = inputStream.read(buffer, 0, 10485760)) != -1) {
						outputStream.write(buffer, 0, readBytes);
						}
				outputStream.close();
				inputStream.close();
				
				/* INSERT FILE INFO TO DB */
				double fileSize = file.getSize();
				fileSize=fileSize/1048576;
			
				String fileName=encrttimestp +"_"+file.getOriginalFilename();
				String filePath="users/member/";
				MyuploadModel myUpload=new MyuploadModel();
				myUpload.InsertMyupload(fileTitle,Integer.parseInt(fileCategory), fileDescription, fileSize, fileName, filePath,fileKeyword,Integer.parseInt(session.getAttribute("user_id").toString()));
				// Go to success page
				response.sendRedirect("upload_success.html");
				}
			}

			// ..........................................
			session.setAttribute("uploadFile", file.getOriginalFilename());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	// RESULTSET TO ARRAYLIST
	   public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException{
		    ResultSetMetaData md = rs.getMetaData();
		    int columns = md.getColumnCount();
		    ArrayList results = new ArrayList();
		    while (rs.next()){
		    HashMap row = new HashMap();
		    results.add(row);
		    for(int i=1; i<=columns; i++){
		    row.put(md.getColumnName(i),rs.getObject(i));
		    }
		    }
		    return results;

	    }
}
